import os
import platform
import subprocess
from pathlib import Path

def is_folder_cunzai(folderpath,auto_create=False):
    """
    判断文件夹是否存在
    :param auto_create: 是否自动创建
    :param folderpath: 文件夹路径
    :return: bool
    """
    if Path(folderpath).is_dir():
        return True
    else:
        if auto_create:
            return create_folderpath(folderpath)
        else:
            return False


def ensure_parent_directory_exists(file_path):
    """
    创建指定路径的父目录
    """
    # 创建一个Path对象
    path = Path(file_path)

    # 获取父目录
    parent_dir = path.parent

    # 如果父目录不存在，则创建它（包括所有必要的上级目录）
    if not parent_dir.exists():
        parent_dir.mkdir(parents=True, exist_ok=True)
def create_folderpath(folderpath):
    """
    创建文件夹
    :param folderpath: 文件夹路径
    :return: bool，True为创建成功，False为创建失败
    """
    try:
        Path(folderpath).mkdir(parents=True, exist_ok=True)  # parents=True 表示创建所有必要的父文件夹
        return True
    except:
        return False


def open_folder(folder_path):
    """
    打开文件夹
    有except报错
    :param folder_path: 文件夹路径
    :return:无
    """
    if platform.system() == "Windows":
        os.startfile(folder_path.replace("/", "\\"))
    elif platform.system() == "Darwin":
        subprocess.Popen(["open", folder_path])
    else:  # Assume Linux or other Unix-like systems
        try:
            subprocess.Popen(["xdg-open", folder_path])
        except FileNotFoundError:
            # Attempt to determine the Linux distribution and use a fallback file manager
            distro = ""
            with open("/etc/os-release") as f:
                for line in f:
                    if line.startswith("ID="):
                        distro = line[3:].strip().strip("\"")
                        break

            if distro == "ubuntu":
                # Ubuntu typically uses Nautilus
                subprocess.Popen(["nautilus", folder_path])
            elif distro == "neon":
                # KDE Neon typically uses Dolphin
                subprocess.Popen(["dolphin", folder_path])
            else:
                raise Exception("Unable to find a suitable file manager.")
        except Exception as e:
            print(f"An error occurred: {e}")
            raise

def get_file_format(file_path):
    """
    获取文件后缀名，不要点号
    :param file_path: 文件路径
    :return: str
    """

    # 创建一个 Path 对象

    path = Path(file_path)

    # 获取文件的扩展名（包括点号）

    file_extension = path.suffix

    # 如果你只需要扩展名而不带点，可以使用切片去掉点号

    return file_extension[1:] if file_extension else ''